package org.example.localbrowser;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.JsResult;

public class LocalBrowserActivity extends Activity {
	private static final String TAG= "LocalBrowser";
	private final Handler handler= new Handler();
	private WebView webView;
	private TextView textView;
	private Button button;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // find the android controls
        webView = (WebView)findViewById(R.id.web_view);
        textView = (TextView)findViewById(R.id.text_view);
        button = (Button)findViewById(R.id.button);
        
        // turn on the JavaScript on browser
        webView.getSettings().setJavaScriptEnabled(true);
        
        // expose a Java object to JavaScript in the browser
        webView.addJavascriptInterface(new AndroidBridge(), "android");
        
        webView.setWebChromeClient(new WebChromeClient(){
        	@Override
        	public boolean onJsAlert(final WebView view, final String url, final String message, JsResult result)
        	{
        		Log.d(TAG, "onJsAlert(" + view + ", " + url + ", " + message + ", " + result + ")");
        		Toast.makeText(LocalBrowserActivity.this, message, 3000).show();
        		result.confirm();
				return true;// i handled it
        	}
        });
        
        // load file from local
        webView.loadUrl("file:///android_asset/index.html");
    }
    
    /**
     * To call Android Java code from JavaScript, need to define a plain old java object 
     * @author minh.ton
     *
     */
    private class AndroidBridge{
    	public void callAndroid(final String arg)
    	{
    		handler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Log.d(TAG, "callAndroid(" + arg + ")");
					textView.setText(arg);
				}
			});
    	}
    }
    
    
}
